package com.qhit.jdbc;

import com.qhit.jdbc.bean.User;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 测试
 *
 * @author 村头老杨头
 * @version 1.0
 * @date 2021/9/24 10:33
 */
public class TestJDBC {
    //  （1）通过3种方式获得User类对应的反射对象
    @Test
    public void getUserClass() throws ClassNotFoundException {
//        方式一   通过类全名获得
        Class<?> aClass = Class.forName("com.qhit.jdbc.bean.User");
//        方式二   通过类获得
        Class<User> userClass = User.class;
//        方式三 通过对象获得
        Class<? extends User> aClass1 = new User().getClass();
    }

//	（2）通过2种方式获得User类的构造方法对应的反射对象Constructor
    @Test
    public void getConstructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<User> userClass = User.class;
        //方式一
        Constructor<User> constructor = userClass.getConstructor(Integer.class,String.class,Integer.class);
        //方式二
        Constructor<User> declaredConstructor = userClass.getDeclaredConstructor();

        User user = constructor.newInstance(1,"李四");

        user.show();
    }
//	（3）通过2种方式通过反射的方式获得User类的实例对象。
    @Test
    public void getUser() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //方式一
        User user1 = (User)userClass.newInstance();
        //方式二
        User user2 = (User) userClass.getConstructor().newInstance();
    }
//  （4）通过Field对真实对象的属性进行读写操作
    @Test
    public void wrField() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        User user = new User();
        //用户类对象
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //获得类的（username）属性对象 (private)
        Field username = userClass.getDeclaredField("username");
        //user对象设置属性(username)用户名为张三
        //访问权限设置true 允许访问
        username.setAccessible(true);
        username.set(user,"张三");
        System.out.println("User的username存放的值是："+username.get(user));
    }
//	（5）通过Method对象，操作真实对象的show()方法
    @Test
    public void printShow() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User(1, "张三", 18);
//        user.show();
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //方法对象 show方法对象
        Method showMethod = userClass.getMethod("show");
        //调用user对象的show方法
        showMethod.invoke(user);
    }
}
